<?php

namespace app;

use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Response;
use Throwable;
use think\facade\App;

/**
 * 应用异常处理类
 */
class ExceptionHandle extends Handle
{
    /**
     * 不需要记录信息（日志）的异常类列表
     * @var array
     */
    protected $ignoreReport = [
        \Exception::class,
        HttpException::class,
        HttpResponseException::class,
        ModelNotFoundException::class,
        DataNotFoundException::class,
        ValidateException::class,
    ];

    /**
     * 记录异常信息（包括日志或者其它方式记录）
     *
     * @access public
     * @param  Throwable $exception
     * @return void
     */
    public function report(Throwable $exception): void
    {
        
        // 使用内置的方式记录异常日志
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @access public
     * @param \think\Request   $request
     * @param Throwable $e
     * @return Response
     */
    public function render($request, Throwable $e): Response
    {
        \think\facade\Log::record('测试日志信息');
        // 添加自定义异常处理机制
        $exceptionContent = parent::render($request, $e)->getData() . ',报错行数:' . empty($e->getLine()) ? '' : $e->getLine();
        $module = str_replace("app\\", '', \think\facade\App::getNamespace());
        $controller = request()->controller();
        $action = request()->action();
        $fielname = date('H_i_s') . '_' . $module . '_' . $controller . '_' . $action . '.html';
        $execptionPath = \think\facade\App::getRuntimePath() . 'execption' . DIRECTORY_SEPARATOR . date('Ymd');
        mkdirs($execptionPath);
        $filePath = $execptionPath . DIRECTORY_SEPARATOR . $fielname;
        file_put_contents($filePath, $exceptionContent);
        
        if ($module == 'api') {
            //api
            $time = microtime_float() - App::getBeginTime();
            $result = [
                'code' => 2000,
                'message'  => '系统异常',
                'time' => $time ? $time : time(),
                'result' => [],
            ];
            // 参数验证错误
            if ($e instanceof ValidateException) {
                $result['code'] = 422;
                $result['message'] = $e->getError();
                return json($result);
            } else if ($e instanceof HttpException) {
                $result['code'] = $e->getStatusCode();
                $result['message'] = $e->getMessage();
                return json($result);
            } else {
                $result['code'] = $e->getCode() == 0 ? 2000 : $e->getCode();
                $result['message'] = $e->getMessage();
                return json($result);
            }
        } else {
            //
            return parent::render($request, $e);
        }

        
    }
}
